<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:include page="../../common.jsp"></jsp:include>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>我已审批</title>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/statics/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/statics/ueditor/ueditor.all.min.js"> </script>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/statics/ueditor/lang/zh-cn/zh-cn.js"></script>
<style type="text/css">
	/*初始化编辑器边框*/
	.edui-default .edui-editor {
	    border: 0px solid #d4d4d4;
	}
	/*初始化编辑器高度,默认320*/
	#edui1_iframeholder{
	    height: 60vh !important
	}
</style> 
<script type="text/javascript">
    //ueditorUE 初始化文本编辑器
    //var ue = UE.getEditor('content');
    var ue = UE.getEditor('html',{
        //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
        toolbars:[],
        //关闭字数统计
        wordCount:false,
        //默认的编辑区域高度
        initialFrameWidth:null,
        //initialFrameHeight:null,  //初始化编辑器高度,默认320
        //更多其他参数，请参考ueditor.config.js中的配置项
    });
    //ueditorUE 去掉本地保存成功的提示框！
    ue.ready(function () {
        $(".edui-editor-messageholder.edui-default").css({ "visibility": "hidden" });
        ue.setDisabled();
    });
</script>
<script type="text/javascript">
$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
	//行点击事件
    oButtonInit.Init();
    $('#tb_table').on('click-row.bs.table', function (e, row, element) {initBottomTable(row.approvalid, row.status03, row.status01);});
	//初始化提示框的位置：top-center，bottom-left，bottom-right
    toastr.options.positionClass = 'toast-top-center';
});


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_table').bootstrapTable({
            url: "${pageContext.request.contextPath}/approval/findAlreadyApproved.do",
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
            strictSearch: true,
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "approvalid",                     //每一行的唯一标识，一般为主键列
            detailView: false,                   //是否显示父子表
            columns:  [ {
                checkbox: true
            },{
				field : 'approvalid',
				visible : false
			},{
				field : 'applicant',
				align : 'center',
				title : '项目名称',
				formatter: function (value, row, index) {
					var nr = htmlnr(row.approvalid,1);
					if(nr == -1){
						nr = ""
					}
					return nr
				}
			},{
				field : 'applicant',
				align : 'center',
				title : '项目说明',
				formatter: function (value, row, index) {
					var nr = htmlnr(row.approvalid,2);
					if(nr == -1){
						nr = ""
					}
					return nr
				}
			},{
				field : 'applicant',
				align : 'center',
				title : '申请人'
			},{
				field : 'status03',
				align : 'center',
				title : '申请类型'
			}, {
				field : 'remark05',
				align : 'center',
				title : '发起时间'
			}, {
				field : 'status01',
				align : 'center',
				title : '状态',
				formatter: function (value, row, index) {
                	if (value.indexOf('2') != -1) {
                		return '已回退';
					} else {
						return '审批通过';
					}
                }
			}/* , {
				field:'title',
                title:"预览",
                align:'center',
                formatter : function(cell, row, index) {
                	if (row.status03 == '合同协议') {
                		cell ='<button type="button" id="btn_preview" class="btn btn-primary" onclick="displayPreview('+row.approvalid+')">预览</button>';
	                    return cell;
					} else {
						return '';
					}
                }
			}, {
				field : 'remark05',
				align : 'center',
				title : '历史批注',
				formatter: function (value, row, index) {
					cell ='<button type="button" class="btn btn-primary" onclick="annotationView('+row.approvalid+')">历史批注</button>';
                    return cell;
				} 
			}*/
			/* } ,{
				field:'title',
                title:"附件预览",
                align:'center',
                formatter : function(cell, row, index) {
                	if (row.status03 != '合同协议') {
                		var val = row.remark06;
						if (val == '') {
							return '';
						} else {
							//cell ="<button type='button' class='btn btn-primary' onclick='docView(\""+val+"\")'>附件预览</button>";
							cell = "<a href='${pageContext.request.contextPath}/attachment/"+val+"' target='_blank' class='btn btn-primary'>下载</a>"
							return cell;
						}
					} else {
						return '';
					}
                }, */
			],
			
			// 注册加载子表的事件
            onExpandRow: function (index, row, $detail) {
            	 initSubTable(index, row, $detail);
            }
        });
	    //合同协议详情
	    $('#tb_departmentsDetailed').bootstrapTable({
	        method: 'get',                      //请求方式（*）
	        striped: true,                      //是否显示行间隔色
	        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
	        pagination: true,                   //是否显示分页（*）
	        sortable: false,                     //是否启用排序
	        sortOrder: "asc",                   //排序方式
	        queryParams: oTableInit.queryParamsDetailed,//传递参数（*）
	        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
	        pageNumber:1,                       //初始化加载第一页，默认第一页
	        pageSize: 10,                       //每页的记录行数（*）
	        pageList: [10, 20, 30],        //可供选择的每页的行数（*）
	        strictSearch: true,
	        minimumCountColumns: 2,             //最少允许的列数
	        clickToSelect: true,                //是否启用点击选中行
	        uniqueId: "aid",                     //每一行的唯一标识，一般为主键列
	        detailView: false,                   //是否显示父子表
	        columns: [{
	            checkbox: true
	        }, {
	            field:'aid',
	            visible: false,
	            title:"编号",
	            align:'center'
	        },{
	            field:'client',
	            visible: false,
	            title:"类别id",
	            align:'center'
	        },{
	            field:'aremark5',
	            title:"类别",
	            align:'center'
	        },{
	            field:'aname',
	            title:"标题",
	            align:'center'
	        },{
	            field:'item',
	            title:"项目归属",
	            align:'center',
					formatter: function (value, row, index) {
						var items =value.split(",");
						if (items.length >= 5) {
							return items[1];
						}else{
							return "";
						}
					}
	        },{
	            field:'item',
	            title:"项目名称",
	            align:'center',
					formatter: function (value, row, index) {
						var items =value.split(",");
						if (items.length >= 5) {
							return items[3];
						}else{
							return "";
						}
					}
	        },{
	            field:'aid',
	            title:"预览",
	            align:'center',
	            width:"80px",
	            formatter : function(cell, row, index) {
	                cell ='<button type="button" id="btn_preview" class="btn btn-primary" onclick="preview('+row.aid+')">预览</button>';
	                return cell;
	            },
	        },],
	    });
    };
 	// 初始化子表
  	function initSubTable(index, row, $detail) {
          var parentid = row.approvalid;
          var cur_table = $detail.html('<table></table>').find('table');
          $(cur_table).bootstrapTable({
            url: '${pageContext.request.contextPath}/approval/packageDetail/'+parentid+'.do',
            striped: true,
  			showColumns: true,
  			minimumCountColumns: 2,
  			showColumns: false,
  			clickToSelect: false,
  			detailView: false,
  			detailFormatter: 'detailFormatter',
  			pagination: false,
  			paginationLoop: false,
  			sidePagination: 'server',
  			silentSort: false,
  			smartDisplay: false,
  			escape: true,
  			idField: 'id',
  			maintainSelected: false,
  			checkboxHeader: false,
            columns: [
  				{field: 'name', title: '项目名称', sortable: true, align: 'left'}],
          });
    };

    
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        	offset: params.offset/params.limit+1,   //页面大小
        	limit: params.limit,  //页码
        	applicant:$.trim($('#appc').val()),
        	status03:$.trim($('#status03c').val()),
        };
        return temp;
    };
	////合同协议详情得到查询的参数
    oTableInit.queryParamsDetailed = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
       		page: params.offset/params.limit+1,   //页面大小
            rows: params.limit,  //页码
            aremark:$.trim($('#id').val()), 
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};



//刷新表格
function seach() {
	$("#tb_table").bootstrapTable("refreshOptions",{pageNumber:1});
}

//预览
function htmlnr(approvalId,num){
	var nr = "";
	$.ajax({
        url: '/agreement/selectAgreementByExample.do' ,
        type: 'post',
        async:false,
        dataType:'json',
        data:"aremark="+approvalId,
        success: function (data) {
            if(data.length > 1){
                for(var i = 0; i < data.length; i++){
	                if(data[i].aremark5 == "呈批件"){
	                	nr = tableHtmlnr(data[i].html,"table",num);
		                break;
	                }
                }
            }
        },
    });
	return nr;
}

//把审批内容添加入呈批件内容（替换表格里第一个*）中
function tableHtmlnr(data,s,num) {
    //返回数据
    var dept = "*";
    var html = "";
    //标签头
    var tableq = "<"+s
	//标签尾
    var tableh = "</"+s+">"
    //标签头分组
    var strks = data.split(tableq);
    //标签尾分组
    var strjs = data.split(tableh);

    for (var i=0;i<strks.length;i++) {
        if(i == 0){
            
        }else {
        	//获取相同值（table内容）
            var ss = getMaxStr(strks[i], strjs[i-1].split(tableq)[1])
            var qh = ss.split("{[");
            var hh = ss.split("]}");
            //第num个{[]}的内容
            var html = getMaxStr(qh[num], hh[num-1].split("{[")[1])
        }
    }
    return html;
}
    
//获取俩字符中相同字段
function getMaxStr(str1,str2){
    var max = str1.length > str2.length ? str1 : str2;
    var min = (max == str1 ? str2 : str1);
    for(var i = 0; i < min.length; i++){
        for(var x = 0, y = min.length - i;y != min.length + 1;x++,y++){
            //y表示所取字符串的长度
            var newStr = min.substring(x,y);
            //判断max中是否包含newStr
            if(max.indexOf(newStr) != -1){
                return newStr;
            }
        }
    }
    return -1;
}


//预览
function displayPreview(approvalId){
	//alert(approvalId)
	/* $.ajax({
        url: '${pageContext.request.contextPath}/approval/queryHTMLByAppId.do' ,
        //dataType: 'json',
        type: 'post',
        data:{"approvalId":approvalId},
        success: function (data) {
        	var jsonObj = eval('(' + data + ')');
        	console.log(jsonObj.html);
            if(jsonObj.html == null){
                toastr.warning('该内容为空');
            }else{
                ue.setContent(jsonObj.html);
                $('#exampleModal').modal(open);
            }
        },
        error: function (data){
        	alert(jsonObj.html)
        }
    }); */
    
    var row=$("#tb_table").bootstrapTable('getSelections');
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	}else{
		var approvalId = row[0].approvalid; 
		$.ajax({
	        url: '/agreement/selectAgreementByExample.do' ,
	        type: 'post',
	        async:false,
	        dataType:'json',
	        data:"aremark="+approvalId,
	        success: function (data) {
	            if(data.length <= 0){
	                toastr.warning('该内容为空');
	            }else if(data.length == 1){
	                ue.setContent(data[0].html);
	                $('#exampleModal').modal(open);
	            }else{
	                for(var i = 0; i < data.length; i++){
		                if(data[i].aremark5 == "呈批件"){
		                	ue.setContent(data[i].html);
			                $('#exampleModal').modal(open);
			                break;
		                }
	                }
	            }
	        },
	    });
	}
}
//合同协议详情内容预览
function preview(tid) {
    $.ajax({
        url: '/agreement/selectAgreementById.do' ,
        type: 'post',
        async:false,
        dataType:'json',
        data:"id="+tid,
        success: function (data) {
            if(data.html == null){
                toastr.warning('该内容为空');
            }else{
                ue.setContent(data.html);
                $('#exampleModal').modal(open);
            }
        },
    });
}
//附件预览
function docView(docPath){
	$.ajax({
        url: '${pageContext.request.contextPath}/approval/docToHtml.do' ,
        type: 'post',
        async: false,
        data:{"docPath":docPath},
        success: function (realPath) {
        	//alert("${pageContext.request.contextPath}/attachment/" + realPath.trim());
        	window.open("${pageContext.request.contextPath}/attachment/" + realPath.trim());
        }
    });
}
</script>
</head>
<body>
	<div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-body" style="padding: 5px;">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px;margin: 0px;">
                        <label class="control-label col-sm-1" for="preHtmlTJ">申请类型</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="status03c">
                        </div>
						<label class="control-label col-sm-1" for="titleTJ">申请人</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="appc">
                        </div>
                        <div class="col-sm-4">
                            <button type="button" style="margin-left: 5%;" id="btn_query" class="btn btn-primary" onclick="seach()">查询</button>
                        	&nbsp;&nbsp;
                        	<button id="btn_add" type="button" class="btn btn-primary" onclick="annotationView()">历史批注 </button>
                        	&nbsp;&nbsp;
                        	<button id="btn_add" type="button" class="btn btn-primary" onclick="displayPreview()">预览</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <table id="tb_table"></table>
        <!--    底部详情表格   -->
        <div id="detail" class="bootstrap-table">
        	<div  style="display:none;" id="xmDiv">
      			<input type="hidden" id="id" value="0">
      			<table id="tb_departmentsDetailed"></table>
      		</div>
        	<div id="fXmDiv" class="fixed-table-container">
        		<div class="fixed-table-header">
        			<table class="table table-hover table-striped">
		        		<thead>
		        			<tr id="thead_tr1">
		        			</tr>
		        		</thead>
		        	</table>
        		</div>
        		<div class="fixed-table-body">
        			<table class="table table-hover table-striped" style="margin-top: -40px;">
		        		<thead>
		        			<tr id="thead_tr2">
		        			</tr>
		        		</thead>
		        		<tbody>
		        			<tr id="tbody_tr">
		        			</tr>
		        		</tbody>
		        	</table>
        		</div>
        	</div>
        </div>
    </div>
	<div class="modal fade bs-example-modal-lg" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    	<div class="modal-dialog modal-lg" role="document">
        	<div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close closefm" data-dismiss="modal" aria-label="Close">
	                    <span aria-hidden="true">&times;</span>
	                </button>
	                <h4 class="modal-title" id="exampleModalLabel">
	                    <span style="font-size:13px">预览</span>
	                    &nbsp;&nbsp;&nbsp;&nbsp;
		                <button type="button" class="btn btn-default" onclick="dy()">
		                    <span class="glyphicon glyphicon-print" aria-hidden="true"></span>
		                </button>
	                </h4>
	                <script type="text/javascript">
	                    function dy() {
	                    	var css="<style>"
	                            +"table {border-collapse: collapse;" +
	                                "border:1px #ddd solid;" +
	                           "}"
	                           +"table tr td {" +
	                                "border:1px #ddd solid;" +
	                           "}"
	                            +"</style>";
	                        var printHtml = css + ue.getContent();
	                    	printpage(printHtml)
	                    }
	                   
	                    function printpage(printHtml){    
	                    	var wind = window.open("",'newwindow', 'top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no');
	                    	wind.document.body.innerHTML = printHtml;
	                    	wind.print();
	                    	return false; 
	                    }
	                </script>
	            </div>
	            <div class="modal-body" >
	                <textarea id="html" name="html"></textarea>
	            </div>
        	</div>
    	</div>
    </div>
    <!-- 批注信息  -->
	<div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content" style="width: 700px;">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span id="bt" style="font-size:13px">历史批注</span>
        			</h4>
      			</div>
      			<div class="modal-body" id="annotationInfo" style="height: 400px;">
	      		</div>
    		</div>
  		</div>
	</div>
</body>
<script type="text/javascript">
	function annotationView(approvalId) {
		 var row=$.map($("#tb_table").bootstrapTable('getSelections'),function(row){
				return row ;
			});
			if (row.length == 0) {
				toastr.warning('请至少选择一条数据!');
			}else{
				var approvalId = row[0].approvalid; 
				$('#exampleModal2').modal(open);
				$('#annotationInfo').empty();
				jQuery("#annotationInfo").load("${pageContext.request.contextPath}/approval/findAnnotationInfoByID.do?approvalId="+approvalId);
			}
	}
</script>
<script>
	//底部详情列表初始化
	function initBottomTable(approvalId, status03, status01){
		/* if ('合同协议' != status03) {
			$.ajax({
	            type: "post",
	            url: "${pageContext.request.contextPath}/initiateMana/findDetailByID.do?approvalId="+approvalId,
	            dataType: "json",
	            success: function(data){
	            	$('#thead_tr1').empty();
					$('#thead_tr2').empty();
					$('#tbody_tr').empty();
	            	var fields = data.mFields.split(',');
					var values = data.mValues.split(',');
					var theadHtml = '';
					var tbodyHtml = '';
					for (var i = 0; i < fields.length; i++) {
						theadHtml = theadHtml + '<th style="text-align: center; " data-field="applicant"><div class="th-inner ">'+
							fields[i] + '</div><div class="fht-cell" style="width: 151px;"></div></th>';
						tbodyHtml = tbodyHtml + '<td style="text-align: center;width: ' + (100/fields.length) + '%;">' + values[i] + '</td>';
					}
					$('#thead_tr1').append(theadHtml);
					$('#thead_tr2').append(theadHtml);
					$('#tbody_tr').append(tbodyHtml);
	            }
	        });
			$("#fXmDiv").show();
			$("#xmDiv").hide();
			
		}else{ */
			 var opt1 = {url: "${pageContext.request.contextPath}/agreement/selectAgreementList.do",};
			 var opt2 = {url: "${pageContext.request.contextPath}/approval/selectAgreementByAremark2.do",};
			
			if (status01.indexOf('2') != -1) {
				$("#id").val(approvalId);
		        $('#tb_departmentsDetailed').bootstrapTable('refresh', opt2);
		        $("#xmDiv").show();
				$("#fXmDiv").hide();	
			} else {
				$("#id").val(approvalId);
		        $('#tb_departmentsDetailed').bootstrapTable('refresh', opt1);
		        $("#xmDiv").show();
				$("#fXmDiv").hide();	
			}
		/* } */
	}
</script>
</html>
